from world_object import WorldObject
import constants
import pygame
import data

class String(WorldObject):
    """Understands a piece of string which can burn"""
    
    def __init__(self, x = 0, y = 0, length = 10):
        WorldObject.__init__(self, x, y,)
        self._length = length
        self.image = pygame.Surface((constants.STRING_WIDTH, self._length))
        self.visible_image = WorldObject()
        self.visible_image.load_sprites(('string.png',))
        self.spark = WorldObject()
        self.spark.load_sprites(('spark1.png','spark2.png','spark3.png'))
        self.decorations = [self.visible_image, self.spark]

        self.update_surface()

    def update_surface(self):
        img_rect = self.image.get_rect()
        img_rect.height = self._length
        self.shrink(self)
        self.update_spark()
        self.update_visible_image()

    def update_spark(self):
        self.spark.change_to_random_sprite()
        new_spark_x = self.position()[0] + (self.image.get_width() / 2) - (self.spark.image.get_width() / 2)
        new_spark_y = self.position()[1] + self._length - (self.spark.image.get_height() / 2)
        self.spark.set_position(new_spark_x, new_spark_y)

    def update_visible_image(self):
        self.visible_image.change_to_random_sprite()
        new_x = self.position()[0] - (self.visible_image.image.get_width() / 2)
        new_y = self.position()[1]
        self.visible_image.set_position(new_x, new_y)
        self.shrink(self.visible_image, offset=2)

    def shrink(self, obj, offset=0):
        img_rect = obj.image.get_rect()
        img_rect.height = self._length + offset
        try: obj.image = obj.image.subsurface(img_rect) #XXX is this leaking memory?
        except: pass
        
    def burn(self, amount = constants.STRING_BURN_SPEED):
        if self._length == 0 or amount <= 0:
            return
        if self._length < amount:
            self._length = 0
        else:
            self._length = self._length - amount
        if self._length == 0:
            self.die()
            
    def length(self):
        return self._length
    
    def tick_update(self):
        WorldObject.tick_update(self)
        self.burn()
        self.update_surface()

    def __str__(self):
        return "string %s, length %s" % (WorldObject.__str__(self), self._length)
    
    @staticmethod
    def highest_string(str1, str2):
        if str1.position()[1] < str2.position()[1]:
            return str1
        return str2

    @staticmethod
    def lowest_string(str1, str2):
        highest = String.highest_string(str1, str2)
        if highest == str1: return str2
        return str1
